package com.scanx.thread.directory;

import com.scanx.conf.CommonConf;
import com.scanx.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 处理待扫描路径
 *
 * @author alpha.
 * @className DirectoryScanThread
 * @date 2024/2/6 14:42
 */
@Slf4j
public class PathScanThread implements Runnable {

    private File file;

    ThreadPoolExecutor executor;

    public PathScanThread(File file, ThreadPoolExecutor executor) {
        this.file = file;
        this.executor = executor;
    }

    @Override
    public void run() {
        if (FileUtil.isEffective(file)) {


            //如果存在，且是文件则直接存入
            if (file.isFile()) {

                if (isIgnore(file)) {
                    return;
                }


                String path = file.getPath();
                try {
                    //put方法如果队列达到最大值则会阻塞
                    AnalyzeQueue.ANALYZE_QUEUE.put(path);
                    log.info("识别到文件：" + path);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return;
            }

            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    executor.execute(new PathScanThread(f, executor));
                }
            }
        }
    }

    /**
     * 检查是否是忽略的文件
     *
     * @param file 待检查文件
     * @return 是否忽略
     */
    private boolean isIgnore(File file) {
        String extension = FilenameUtils.getExtension(file.getName());
        return CommonConf.IGNORE_SUFFIX.contains(extension);
    }
}
